package kr.haggenna.member.controller;

import java.util.List;

import javax.annotation.Resource;

import kr.haggenna.member.dao.MemberDao;
import kr.haggenna.member.domain.MemberCommand;
import kr.haggenna.member.util.CipherTemplate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FindEmailpassController {
	
	@Autowired
	private MemberDao memberDao;
	
	@Resource(name="cipherAES")
	private CipherTemplate cipherAES;
	
	@ModelAttribute
	public MemberCommand formBacking(){
		return new MemberCommand();
	}
	
	@RequestMapping("/findEmailpass.do")
	public String process() {
		return "findEmailpass";
	}
	
	@RequestMapping(value="/findEmail.do",method=RequestMethod.POST)
	public ModelAndView submit( @ModelAttribute("memberCommand")MemberCommand memberCommand, BindingResult result,
								@RequestParam("count") int count){
		
		ModelAndView mav = new ModelAndView();

		List<MemberCommand> memberList = memberDao.getMemberList();
		
		boolean flag = false;
		
		if(memberList != null){
			for(MemberCommand m : memberList){
				if(m.getName().equals(memberCommand.getName()) && m.getPhone().equals(memberCommand.getPhone())){
					flag = true;
				}
			}
		}
		
		if(flag == true){
			count = 1;
		} else if(flag == false){
			count = 0;
		}
		
		MemberCommand member = memberDao.findEmail(memberCommand);
		
		mav.setViewName("findEmailpass");
		mav.addObject("count", count);
		mav.addObject("member", member);
		
		return mav;
	}
	
	@RequestMapping(value="/findPass.do",method=RequestMethod.POST)
	public ModelAndView sub(@ModelAttribute("memberCommand")MemberCommand memberCommand, BindingResult result,
							@RequestParam("count") int count){
		ModelAndView mav = new ModelAndView();
		
		List<MemberCommand> memberList = memberDao.getMemberList();
		
		boolean flag = false;
		
		if(memberList != null){
			for(MemberCommand m : memberList){
				if(m.getName().equals(memberCommand.getName()) && m.getEmail().equals(memberCommand.getEmail())){
					flag = true;
				}
			}
		}
		
		MemberCommand member = memberDao.findPasswd(memberCommand);
		
		if(flag == true){
			member.setPasswd(cipherAES.decrypt(member.getPasswd()));
			count = 2;
		} else if(flag == false){
			count = 3;
		}
		
		mav.setViewName("findEmailpass");
		mav.addObject("count", count);
		mav.addObject("member", member);
		
		return mav;
	}
	
}
